package biz.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dao.UserDAO;
import system.MTO;
import system.RunTimeData;
import system.StaticData;
import system.bean.ClientCode;
import system.bean.UserState;
import entity.Group;
import entity.User;
import biz.interfaces.IUserBiz;
import biz.util.YwsOLUtil;

class UserBiz implements IUserBiz {

	private GroupBiz groupBiz = null;
	private UserDAO userDAO = null;

	@Override
	public MTO UserLogin(User user) throws IOException {

		MTO mto = new MTO();

		if (user == null || user.getYwsLoginName() == null
				|| user.getYwsPassWord() == null) {

			mto.setClientCode(ClientCode.UNKNOW_ERROR_ON_LOGIN);
			return mto;
		}
		String url = StaticData.LOGIN_URL;

		url = url.replaceFirst("#username#", user.getYwsLoginName());
		url = url.replaceFirst("#password#", user.getYwsPassWord());
		Map<String, String> result = YwsOLUtil.GetHTMLandSessionIDByURL(url, null);

		
		String html = result.get("html");
		
		if (html.indexOf(StaticData.LOGIN_SUCCESS_FLAG) >= 0) {

			String sessionid = result.get("sessionid");

			mto.setSuccess(true);
			mto.setClientCode(ClientCode.LOGIN_SUCCESS);
			
			//如果是首次加入，则到雨无声获取ID、头像，并保存到DB
			if(!isExistByLoginName(user.getYwsLoginName())){
				String r1 = YwsOLUtil.GetHTMLByURL(StaticData.GET_YWSID_URL, sessionid);
				
				
				int ywsid = Integer.parseInt(YwsOLUtil.GetFromStringByBeforeAfter(r1, StaticData.YWSID_BEFORE, StaticData.YWSID_AFTER, false));
				String u2 = StaticData.YWS_GET_PERSON_INFO_URL;
				u2 = u2.replaceFirst("#userid#", Integer.valueOf(ywsid).toString());
				String r2 = YwsOLUtil.GetHTMLByURL(u2, sessionid);
			
				String facePath = YwsOLUtil.GetFromStringByBeforeAfter(r2, StaticData.FACE_URL1_BEFORE, StaticData.FACE_URL1_AFTER, true);
				if(facePath == null)
					facePath = YwsOLUtil.GetFromStringByBeforeAfter(r2, StaticData.FACE_URL2_BEFORE, StaticData.FACE_URL2_AFTER, true);
				
				if(facePath == null)
					facePath = YwsOLUtil.GetFromStringByBeforeAfter(r2, StaticData.FACE_URL3_BEFORE, StaticData.FACE_URL3_AFTER, true);
				
				
				
				
				String nickname = YwsOLUtil.GetFromStringByBeforeAfter(r1, StaticData.NICKNAME_BEFORE, StaticData.NICKNAME_AFTER, true);
				
				
				User newUser = new User();
				newUser.setJoinTime(YwsOLUtil.GetNowTime());
				newUser.setYwsId(ywsid);
				newUser.setYwsLoginName(user.getYwsLoginName());
				newUser.setYwsNickName(nickname);
				newUser.setFacePath(facePath);

				userDAO.AddUser(newUser);
				int userid = userDAO.GetUserIdByLoginName(user.getYwsLoginName());
				
				
				
				DownLoadUserFace(userid, facePath);

				List<Group> groupList = new ArrayList<Group>();
				
				//为新用户添加好友分组
				Group group1 = new Group();
				group1.setGroupname("我的同学");
				group1.setUserId(userid);
				
				Group group2 = new Group();
				group2.setGroupname("黑名单");
				group2.setUserId(userid);
				groupList.add(group1);
				groupList.add(group2);
				groupBiz.AddGroupList(groupList);

			}
			
			int userid = userDAO.GetUserIdByLoginName(user.getYwsLoginName());
			Map<String, Object> mtoData = new HashMap<String, Object>();
			User u = userDAO.GetUserByID(userid);
			
			mtoData.put("userid", userid);

			List<Group> grouplist = groupBiz.GetGroupListByUserID(userid);

			//获取好友昵称
			for (int i=0; i<grouplist.size();i++) {
				Group group = grouplist.get(i);
				group.setUserId(null);	//不想让客户端看到自己的ID
				String friendString = group.getFriendString();
				if(friendString.trim().equals(""))
					continue;

				StringBuffer sb = new StringBuffer("");
				String[] friendItems = friendString.split(" ");
				
				for (String friendItem : friendItems) {
					if(friendItem.trim().equals(""))
						continue;
					int memoIndex = friendItem.indexOf("$");

					Integer uid = Integer.parseInt((memoIndex < 0 ? friendItem.substring(0) : friendItem.substring(0, memoIndex)));

					sb.append(uid + "'" + userDAO.GetNickNameByID(uid));
					if(memoIndex > 0)
						sb.append(friendItem.substring(memoIndex));
					
					//在线：<
					//离线：>
					sb.append(RunTimeData.Get(uid) != null ? "<":">");
					sb.append(userDAO.GetHeartByID(uid));
					sb.append(" ");
				}

				group.setFriendString(sb.toString().trim());

			}
			
			Map<String, String> myInfoMap = new HashMap<String, String>();
			myInfoMap.put("myid", String.valueOf(userid));

			myInfoMap.put("mynickname", u.getYwsNickName());
			myInfoMap.put("myheart", u.getHeart());
			mtoData.put("myinfo", myInfoMap);	//本人信息
			
			mtoData.put("groups", grouplist);
			
			mto.setDataObject(mtoData);
			
			
			//添加用户对象
			UserState userState = new UserState();
			userState.setUserID(userid);
			userState.setLastActiveTime(new Date());
			RunTimeData.Add(userid, userState);
//			System.out.println("添加用户对象  " + userid);


		} else if (html.indexOf(StaticData.LOGIN_VALIDATE_ERROR_FLAG) >= 0)
			mto.setClientCode(ClientCode.ERROR_USERNAME_OR_PASSWORD);
		else if (html.indexOf(StaticData.LOGIN_NO_OPEN_FLAG) >= 0)
			mto.setClientCode(ClientCode.NO_OPEN);
		else
			mto.setClientCode(ClientCode.UNKNOW_ERROR_ON_LOGIN);

		return mto;

	}
	

	private boolean isExistByLoginName(String loginName){
		return userDAO.GetUserCountByLoginName(loginName) == 1 ?true:false;
	}

	
	@Override
	public void DownLoadUserFace(Integer userid, String faceUrl) {
		if(faceUrl == null || faceUrl.indexOf(";") >= 0)
			return;
		
		String httpFacePath = StaticData.YWS_GET_PERSON_INFO_URL;
		//httpFacePath = httpFacePath.substring(0, httpFacePath.lastIndexOf("/"));
		if(faceUrl.indexOf("/") == 0){
			int i1 = httpFacePath.indexOf("/", 7);
			httpFacePath = httpFacePath.substring(0, i1) + faceUrl;
		}else{
			httpFacePath = httpFacePath.substring(0, httpFacePath.lastIndexOf("/") + 1);
		}

		YwsOLUtil.DownloadByURL(httpFacePath, StaticData.FACE_REFERER_URL, StaticData.YWSLISTENER_SESSIONID,
				StaticData.PROJECT_LOCATION + "image/userfaces/" + userid + ".jpg");
	}
	
	
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}


	public void setGroupBiz(GroupBiz groupBiz) {
		this.groupBiz = groupBiz;
	}

}
